# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=qt5

_configure=./configure.bat
#_configure=./configure
# When using the configure bash script, MSYS2 make is
# probably a better choice as otherwise the Makefiles
# can have MSYS2 paths in them. We try to handle this
# but it is ad-hoc at best.
_make=make
#_make=${MINGW_PREFIX}/bin/mingw32-make
#_opengl=angle
_opengl=desktop
_opengl_for_configure="${_opengl}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
_ver_base=5.3.1
pkgver=${_ver_base//-/}
pkgrel=2
arch=('any')
pkgdesc="A cross-platform application and UI framework (mingw-w64)"
url='http://qt-project.org/'
install=qt5-${CARCH}.install
license=('GPL3' 'LGPL' 'FDL' 'custom')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-dbus"
         "${MINGW_PACKAGE_PREFIX}-fontconfig"
         "${MINGW_PACKAGE_PREFIX}-freetype"
         "${MINGW_PACKAGE_PREFIX}-harfbuzz"
         "${MINGW_PACKAGE_PREFIX}-icu-debug-libs"
         "${MINGW_PACKAGE_PREFIX}-jasper"
         "${MINGW_PACKAGE_PREFIX}-libjpeg"
         "${MINGW_PACKAGE_PREFIX}-libmng"
         "${MINGW_PACKAGE_PREFIX}-libpng"
         "${MINGW_PACKAGE_PREFIX}-libtiff"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-libxslt"
         "${MINGW_PACKAGE_PREFIX}-libwebp"
         "${MINGW_PACKAGE_PREFIX}-openssl"
         "${MINGW_PACKAGE_PREFIX}-pcre"
         "${MINGW_PACKAGE_PREFIX}-qtbinpatcher"
         "${MINGW_PACKAGE_PREFIX}-sqlite3"
         "${MINGW_PACKAGE_PREFIX}-xpm-nox"
         "${MINGW_PACKAGE_PREFIX}-zlib"
)

makedepends=("bison"
             "diffutils"
             "flex"
             "gperf"
             "m4"
             "make"
             "patch"
             "perl"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-libmariadbclient"
             "${MINGW_PACKAGE_PREFIX}-libfbclient"
             "${MINGW_PACKAGE_PREFIX}-postgresql"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python2"
             "${MINGW_PACKAGE_PREFIX}-ruby"
             "${MINGW_PACKAGE_PREFIX}-make"
             )
groups=("${MINGW_PACKAGE_PREFIX}-qt" "${MINGW_PACKAGE_PREFIX}-qt5")
options=('!strip' 'staticlibs')
_pkgfqn="qt-everywhere-opensource-src-${_ver_base}"
source=(#"${_pkgfqn}.tar.xz"
        #http://download.qt-project.org/development_releases/qt/${pkgver%.*}/${_ver_base//RC/rc}/single/${_pkgfqn}.tar.xz
        http://download.qt-project.org/official_releases/qt/${pkgver%.*}/${_ver_base}/single/${_pkgfqn}.tar.xz
        #http://download.qt-project.org/snapshots/qt/${pkgver%.*}/${_ver_base}/2014-05-07_85/src/qt-everywhere-opensource-src-${_ver_base}.tar.xz
        #"qt3d"::"git://gitorious.org/qt/qt3d.git"
        0001-qt-5.3.0-oracle-driver-prompt.patch
        0002-qt-5.3.0-use-fbclient-instead-of-gds32.patch
        0003-qt-5.3.0-use-mingw-built-mysql-library.patch
        0004-qt-5.3.0-win32-g++-mkspec-optimization.patch
        0005-qt-5.3.0-syncqt-fix.patch
        0006-qt-5.3.0-win_flex-replace.patch
        0007-qt-5.3.0-win32-g-Enable-static-builds.patch
        0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
        0009-qt-5.3.0-qmlimportscanner-Ensure-the-correct-variant-is-run.patch
        0010-qt-5.3.0-qdoc-increase-stack-size-for-win32-g-too.patch
        0011-qt-5.3.0-win32-g++-allow-static-dbus-1.patch
        0012-qt-5.3.0-compileTest-for-icu-after-setting-static-or-shared.patch
        0013-qt-5.3.0-qtwebkit-enable-pkgconfig-support-for-win32-target.patch
        0014-qt-5.3.0-fix-configure-tests.patch
        0015-qt-5.3.0-properly-split-libraries-mingw.patch
        0016-qt-5.3.0-win32-g++-use-qpa-genericunixfontdatabase.patch
        0017-qt-5.3.0-fix-examples-building.patch
        0018-qt-5.3.0-add-angle-support.patch
        0019-qt-5.3.0-qtwebkit-angle-build-fix.patch
        0020-qt-5.3.0-use-external-angle-library.patch
        0021-qt-5.3.0-qtwebkit-dont-use-bundled-angle-libraries.patch
        0022-qt-5.3.0-qtwebkit-angle-update-for-angleproject-76985f-and-51b4a0.patch
        0023-qt-5.3.0-env-set-external-angle.patch
        0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
        0025-qt-5.3.1-force-using-make-on-msys.patch
        0026-qt-5.3.1-webkit-detect-tools.patch
        0027-qt-5.3.1-msys-perl.patch)
md5sums=('f9a24a0d5645efa0715b6ff0fa13d60f'
         'e3210b753ba04762de2ed4cb9c786bf1'
         '356f7fcf93869e92cd232ef70160ab58'
         'b0b5cc641cf8ebc2660fa819bede0089'
         '7dd197353f489ad98ead28980b40e8d8'
         '457b97833220a81f542f529e7e0c549c'
         '89b720a561c4410085a8e4a456f4a39d'
         '0f2e3a2f790b07442f0964f4f2f96596'
         '8ce562d034bb19aaec28ab3abe79bbab'
         'ea5f1d5bf2ea4c1d69e6b5de0765adfb'
         '6914a82ad728ff0da3c959f53367384c'
         'a3d928580732a966bb20e5dd8bc25606'
         '5a735ecec8b12cbd9d48015de4690b87'
         '3b740ce9bca6d9019b09f6f38f07411a'
         'c0721e53378a24b8d013c7db59f14c17'
         '0d7ce23a99b3f15d176c09e617a437f9'
         '40ba7d8134a696d07be5be6692cfaca7'
         'f080b698ff724093e95a7b4f22b407eb'
         'e65e3ed10e2dd98d5402321657c809c4'
         '9ee6524aa78b5e4fbb47f10dc3b267a4'
         'acb49bb963a23b15bc7d1a93d8896bee'
         'd64536bcf72b63d15df106e2c9913154'
         '05e73ac3ead09802111cc13d8e3e28c8'
         '09aaa20fe92aa3fb8eaa36f805503d7d'
         '6384ff636647fce0bc153e42d4aab769'
         '3b550bd6c58d09aa6729987ef16fed65'
         'c89d5c00376d64350c193c4f2459d807'
         '21a72c4dc81ca85714bf5e9880468eef')
translate_for_make() {
  if [ "${_make}" = "make" ]; then
    echo "${1}"
  else
    echo "${1}" | sed "s|${MINGW_PREFIX}|$(cygpath -m ${MINGW_PREFIX})|g"
  fi
}


prepare() {
  # cd ${srcdir}
  # cp -rf qt3d ${_pkgfqn}/
  cd ${_pkgfqn}

  # MSYS2 gperf cannot handle \r\n.
  find . -name "*.gperf" -exec dos2unix "{}" \;

  patch -p1 -i ${srcdir}/0001-qt-5.3.0-oracle-driver-prompt.patch
  patch -p1 -i ${srcdir}/0002-qt-5.3.0-use-fbclient-instead-of-gds32.patch
  patch -p1 -i ${srcdir}/0003-qt-5.3.0-use-mingw-built-mysql-library.patch
  patch -p1 -i ${srcdir}/0004-qt-5.3.0-win32-g++-mkspec-optimization.patch
  patch -p1 -i ${srcdir}/0005-qt-5.3.0-syncqt-fix.patch
  patch -p1 -i ${srcdir}/0006-qt-5.3.0-win_flex-replace.patch

  # My qt-5.3.0 win32-g++ static patches are against qtbase's dev branch.
  pushd qtbase > /dev/null
  patch -p1 -i ${srcdir}/0007-qt-5.3.0-win32-g-Enable-static-builds.patch
    # Despite qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch the following .a (i.e. non-import)
    # static libraries end up being made:
    #   ActiveQt (which is always built statically), libQt5OpenGLExtensions{d}.a, libQt5PlatformSupport{d}.a
    #   libQt5QmlDevTools.a, libQt5UiTools{d}.a libqtmain{d}.a
    patch -p1 -i ${srcdir}/0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
    patch -p1 -i ${srcdir}/0009-qt-5.3.0-qmlimportscanner-Ensure-the-correct-variant-is-run.patch
    patch -p1 -i ${srcdir}/0010-qt-5.3.0-qdoc-increase-stack-size-for-win32-g-too.patch
    patch -p1 -i ${srcdir}/0011-qt-5.3.0-win32-g++-allow-static-dbus-1.patch
    # The next patch needs some work. It's moving a block of shell script un-necessarily
    # as the bit: QMAKE_CONFIG="$QMAKE_CONFIG static" before calling compileTest is what
    # actually made it work. There may be a good reason for not adding static to QMAKE_CONFIG
    # so it might be necessary to back up the value, do compileTest then restore it after.
    patch -p1 -i ${srcdir}/0012-qt-5.3.0-compileTest-for-icu-after-setting-static-or-shared.patch
  popd > /dev/null

  patch -p1 -i ${srcdir}/0013-qt-5.3.0-qtwebkit-enable-pkgconfig-support-for-win32-target.patch
  patch -p1 -i ${srcdir}/0014-qt-5.3.0-fix-configure-tests.patch
  patch -p1 -i ${srcdir}/0015-qt-5.3.0-properly-split-libraries-mingw.patch
  patch -p1 -i ${srcdir}/0016-qt-5.3.0-win32-g++-use-qpa-genericunixfontdatabase.patch
  patch -p1 -i ${srcdir}/0017-qt-5.3.0-fix-examples-building.patch

  if [ "${_opengl}" = "angle" ]; then
    # Hacks to use external ANGLE libraries.
    # These patches needs more work - they're unfinished and break desktop OpenGL
    # patch -p1 -i ${srcdir}/0018-qt-5.3.0-add-angle-support.patch
    # patch -p1 -i ${srcdir}/0019-qt-5.3.0-qtwebkit-angle-build-fix.patch
    patch -p1 -i ${srcdir}/0020-qt-5.3.0-use-external-angle-library.patch
    patch -p1 -i ${srcdir}/0021-qt-5.3.0-qtwebkit-dont-use-bundled-angle-libraries.patch
    patch -p1 -i ${srcdir}/0022-qt-5.3.0-qtwebkit-angle-update-for-angleproject-76985f-and-51b4a0.patch
    patch -p1 -i ${srcdir}/0023-qt-5.3.0-env-set-external-angle.patch
    if [ "${_configure}" = "./configure" ]; then
      _opengl_for_configure=yes
    fi
  fi
  
  patch -p1 -i ${srcdir}/0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
  if [ "${_make}" = "make" ]; then
    patch -p1 -i ${srcdir}/0025-qt-5.3.1-force-using-make-on-msys.patch
  fi
  patch -p1 -i ${srcdir}/0026-qt-5.3.1-webkit-detect-tools.patch
  patch -p1 -i ${srcdir}/0027-qt-5.3.1-msys-perl.patch

  # See: https://bugreports.qt-project.org/browse/QTBUG-37902
  # _ver_num=${_ver_base%%-*}
  # sed -i "s/^MODULE_VERSION = .*$/MODULE_VERSION = ${_ver_num}/g" qtenginio/.qmake.conf

  local _optim=
  case ${MINGW_CHOST} in
    i686*)
      _optim="-march=i686 -mtune=core2"
    ;;
    x86_64*)
      _optim="-march=nocona -mtune=core2"
    ;;
  esac

  # Determine the CFLAGS, DEBUG_CFLAGS and LDFLAGS that we will tell {g++,gcc}-base.conf about
  CFLAGS_MKS_RELEASE="${CFLAGS}"
  CFLAGS_MKS_DEBUG="${CFLAGS} ${DEBUG_CFLAGS}"
  LDFLAGS_MKS="${LDFLAGS}"
  # If not using MSYS2 make then transform -I${MINGW_PREFIX}/blah or -L${MINGW_PREFIX}/blah from MSYS2 to native
  CFLAGS_MKS_RELEASE=$(translate_for_make "${CFLAGS_MKS_RELEASE}")
  CFLAGS_MKS_DEBUG=$(translate_for_make "${CFLAGS_MKS_DEBUG}")
  LDFLAGS_MKS=$(translate_for_make "${LDFLAGS_MKS}")

  sed -i "s|%OPTIMIZE_OPT%|${_optim}|g" qtbase/mkspecs/win32-g++/qmake.conf
  sed -i "s|%STATICFLAGS%||g" qtbase/mkspecs/win32-g++/qmake.conf
  sed -i "s|^QMAKE_CFLAGS_RELEASE *+= .*$|QMAKE_CFLAGS_RELEASE       += ${CFLAGS_MKS_RELEASE}|g" qtbase/mkspecs/common/{g++,gcc}-base.conf
  sed -i "s|^QMAKE_CFLAGS_DEBUG *+= .*$|QMAKE_CFLAGS_DEBUG         += ${CFLAGS_MKS_DEBUG}|g" qtbase/mkspecs/common/{g++,gcc}-base.conf
  sed -i "/^QMAKE_LFLAGS_RPATH/s| -Wl,-rpath,||g" qtbase/mkspecs/common/gcc-base-unix.conf
  sed -i "/^QMAKE_LFLAGS\s/s|+=|+= ${LDFLAGS_MKS}|g" qtbase/mkspecs/common/gcc-base.conf

  # To keep the build folder name quite small (MAXPATH limit)
  # the source folder (long) is renamed to $CARCH (i686 or x86_64)
  [ -d ${CARCH} ] && rm -rf ${CARCH}
  cd ${srcdir}
  mv ${_pkgfqn} ${CARCH}
}

build() {
  cd ${CARCH}
  touch qtbase/.gitignore
  #BUILD_WIN=$(pwd -W)
  #echo "BUILD_WIN $BUILD_WIN"

  mkdir -p ${pkgdir}${MINGW_PREFIX}
  pushd ${pkgdir}${MINGW_PREFIX} > /dev/null
  QTDIR_WIN=$(pwd -W)
  popd > /dev/null

  local _extra_inc_string="$(pkg-config --cflags-only-I dbus-1 libxml-2.0 freetype2) -I${MINGW_PREFIX}/include/GLSLANG"
  local -a _extra_inc
  for _inc in "$(translate_for_make $_extra_inc_string)"; do
    _extra_inc+=("$_inc")
  done

  export EXTERNAL_ANGLE=1
  export PATH="${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}"
  export LIBRARY_PATH="${MINGW_PREFIX}/${MINGW_CHOST}/lib:${MINGW_PREFIX}/lib"

  # Set the correct one of _extra_inc or _extra_inc_string, never both.
  if [ "${_configure}" = "./configure.bat" ]; then
    _extra_inc_string=${_extra_inc_string//-I/:}
    _extra_inc_string=${_extra_inc_string// /}
    unset _extra_inc
    plain "_extra_inc_string (for ${_configure}) is ${_extra_inc_string}"
  else
    _extra_inc_string=""
    plain "_extra_inc (for ${_configure}) is ${_extra_inc[@]}"
  fi

  # Set other config stuff that's configure-script-type dependent.
  local -a _extra_config
  if [ "${_configure}" = "./configure" ]; then
    _extra_config+=("-no-gtkstyle")
    _extra_config+=("-no-glib")
  fi
  export CPATH="${MINGW_PREFIX}/${MINGW_CHOST}/include:${MINGW_PREFIX}/include:${MINGW_PREFIX}/include/noX:${MINGW_PREFIX}/include/mariadb:${_extra_inc_string}"
  # export LIB="${MINGW_PREFIX}/${MINGW_CHOST}/lib:${MINGW_PREFIX}/lib"

  # Qt manages the compiler flags for release / debug configs separately, so having our own values (-O2) is harmful here ..
  unset CFLAGS
  unset CXXFLAGS
  unset LDFLAGS
  
  ${_configure} \
    -prefix ${QTDIR_WIN} \
    -datadir ${QTDIR_WIN}/share/qt5 \
    -archdatadir ${QTDIR_WIN}/share/qt5 \
    -examplesdir ${QTDIR_WIN}/share/qt5/examples \
    -testsdir ${QTDIR_WIN}/share/qt5/tests \
    -opengl ${_opengl_for_configure} \
    -opensource \
    -confirm-license \
    -device-option QMAKE_EXTENSION_IMPORTLIB="dll.a" \
    -platform win32-g++ \
    -shared \
    -debug-and-release \
    "${_extra_inc[@]}" \
    -no-iconv \
    -icu \
    "${_extra_config[@]}" \
    -plugin-sql-ibase \
    -plugin-sql-mysql \
    -plugin-sql-psql \
    -plugin-sql-odbc \
    -openssl \
    -dbus \
    -fontconfig \
    -system-harfbuzz \
    -system-freetype \
    -nomake tests \
    -make-tool ${_make}

  # There is a race condition / dependency problem with libqtiff and dumpdoc.exe which
  # can happen at -j9 so make twice (dumpdoc.exe depends on libqtiff but can get built
  # first).
  ${_make} ${MAKEFLAGS} || ${_make} ${MAKEFLAGS}

  # Fix paths
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" qtwebkit/Source/Makefile.api
}

package() {

  cd ${CARCH}

  export PATH=${pkgdir}${MINGW_PREFIX}/bin:${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}

  ${_make} install
  ${_make} docs
  ${_make} install_qch_docs

  install -D -m644 LGPL_EXCEPTION.txt \
    "${pkgdir}${MINGW_PREFIX}"/share/licenses/qt5/LGPL_EXCEPTION.txt

  # Remove dlls from lib/
  rm -f "${pkgdir}${MINGW_PREFIX}/lib"/*.dll

  # Workaround for installing empty .pc files
  plain "---> Fix pkgconfig files..."
  local _pc_files=( $(find ${srcdir}/${CARCH} -type f -name Qt5*.pc) )
  cp -f ${_pc_files[@]} ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/

  # Fix wrong path in prl files
  # find "${pkgdir}${MINGW_PREFIX}/lib" -type f -name '*.prl' \
  #   -exec sed -i -e '/^QMAKE_PRL_BUILD_DIR/d;s/\(QMAKE_PRL_LIBS =\).*/\1/' {} \;

  # Fix wrong qmake path in pri file
  # sed -i "s|${srcdir}/${CARCH}/qtbase|/usr|" \
  #   "${pkgdir}"/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri
}
